<script setup>
import { introApi } from "@/services/index";
import { onLoad, onShow, onReachBottom, onHide } from "@dcloudio/uni-app";
import { nextTick, ref, watch, onMounted } from "vue";
import { appInfo, loginSwitch } from "@/services/user";
import topNav from "../../components/topNav.vue";
import {
  appStockListQuery,
  appOrderCreate,
  appProductNoCode,
  getProductByBarCode,
} from "@/services/cashier";
import { operation } from "@/utils/num.js";
const topHeight = ref(uni.getStorageSync("topHight") || 0);
onLoad((e) => {});

const saveFun = () => {
  console.log("保存");
};

const listTab = ref([{ name: "热卖" }, { name: "新品" }]);
const active = ref(0);

const keyWord = ref(null);
const priceValue = ref("10.1");
const isPayShow = ref(false);
const sand_code = ref("");

const form = ref({
  pageIndex: 1,
  pageSize: 30,
  keyword: "",
  barCode: "",
  showAll: "false",
  tag: "",
});
const productData = ref([]);
const loading = ref(false);
const payNum = ref(0);
const payPrice = ref(0);

const productDataNo = ref([]);
const selectNo = ref(0);
const userInfo = ref({});

onLoad((e) => {
  uni.removeStorageSync("goods");
  uni.removeStorageSync("goodsNo");

  getAppStockListQuery(1);
  getAppProductNoCode();
  if (uni.getStorageSync("user")) {
    userInfo.value = uni.getStorageSync("user")
      ? JSON.parse(uni.getStorageSync("user"))
      : {};
  } else {
    uni.reLaunch({
      url: "/pages/login/login",
    });
  }
});

const getAppProductNoCode = async () => {
  try {
    let res = await appProductNoCode();
    res.data.datas.forEach((element) => {
      element.orderNum = 1;
    });
    productDataNo.value = res.data.datas;
  } catch (e) {
    console.log(e);
  }
};
const isShowBtn = ref(true);

onShow(async () => {
  let num = 0;
  let price = 0;
  let arr = [];
  let arrNo = [];

  // let res = getProductByBarCode({ barCode: "2200001005006" });

  if (uni.getStorageSync("goods")) {
    arr = JSON.parse(uni.getStorageSync("goods"));

    arr.forEach((item) => {
      productData.value.forEach((item1) => {
        if (item1.id == item.id) {
          item1.orderNum = item.orderNum;
          num = num + item1.orderNum;
          price = operation(
            price,
            operation(
              item.orderNum,
              item.price ? item.price : item.totalPrice,
              2,
              "multiply"
            ),
            2,
            "add"
          );
        }
      });
    });
  }

  if (uni.getStorageSync("goodsNo")) {
    arrNo = JSON.parse(uni.getStorageSync("goodsNo"));

    arrNo.forEach((item) => {
      productDataNo.value.forEach((item1, index1) => {
        if (item1.id == item.id) {
          item1.orderNum = item.orderNum;
          num = num + item1.orderNum;
          price = operation(
            price,
            operation(item.orderNum, item.salePrice, 2, "multiply"),
            2,
            "add"
          );
        }
      });
    });
  }
  if (uni.getStorageSync("goodsNo") || uni.getStorageSync("goods")) {
    payPrice.value = price;
    payNum.value = num;
  }
  if (uni.getStorageSync("barCode")) {
    sand_code.value = uni.getStorageSync("barCode");
    getProductByBarCodeFun();
  }
  // getProductByBarCodeFun();
  isPay.value = false;

  uni.removeStorageSync("goodsNo");
  uni.removeStorageSync("goods");
});

const getProductByBarCodeFun = async () => {
  try {
    // let res = await getProductByBarCode({ barCode: "6974538610199" });
    let res = await getProductByBarCode({ barCode: sand_code.value });

    if (res.code == 200) {
      uni.removeStorageSync("barCode");
      // if

      productData.value.push(res.data);

      payNum.value = payNum.value + res.data.orderNum;
      payPrice.value = operation(
        payPrice.value,
        operation(
          res.data.orderNum,
          res.data.price ? res.data.price : res.data.totalPrice,
          2,
          "multiply"
        ),
        2,
        "add"
      );
      if (uni.getStorageSync("barCode")) {
        uni.removeStorageSync("barCode");
      }
    } else {
      uni.showToast({
        title: res.message,
        icon: "none",
      });
      if (uni.getStorageSync("barCode")) {
        uni.removeStorageSync("barCode");
      }
    }
  } catch (e) {
    uni.showToast({
      title: e.message,
      icon: "none",
    });
    if (uni.getStorageSync("barCode")) {
      uni.removeStorageSync("barCode");
    }
  }
};

onReachBottom(() => {
  getAppStockListQuery();
});

const getAppStockListQuery = async (index) => {
  if (index == 1) {
    productData.value = [];
  }
  if (index) {
    form.value.pageIndex = index;
  }
  loading.value = true;
  form.value.excludeDhCode = true;
  try {
    let res = await appStockListQuery(form.value);
    if (res.code == 200) {
      res.data.datas.forEach((element) => {
        element.orderNum = 0;
      });
      // let resData = res.data.datas;
      productData.value = productData.value.concat(res.data.datas);

      form.value.pageIndex = form.value.pageIndex + 1;
      loading.value = false;
    } else {
    }

    console.log(res);
  } catch (e) {}
};
nextTick(() => {});

const isPay = ref(false);

const goPay = async () => {
  if (isPay.value == true) {
    return;
  }
  isPay.value = true;
  uni.showLoading({
    title: "提交中",
    mask: true,
  });

  let data = [];
  let dataList = [];
  let dataListNo = [];
  productData.value.forEach((element) => {
    if (element.orderNum > 0) {
      dataList.push(element);
      data.push({
        productId: element.id,
        orderNum: element.orderNum,
      });
    }
  });
  productDataNo.value.forEach((element) => {
    if (element.orderNum > 0 && element.salePrice > 0) {
      dataListNo.push(element);
      data.push({
        productId: element.id,
        orderNum: element.orderNum,
        price: element.salePrice,
      });
    }
  });

  if (data.length <= 0) {
    isPay.value = false;
    return uni.showToast({
      title: "请选择商品",
      icon: "none",
    });
  }

  uni.setStorageSync("goods", JSON.stringify(dataList));
  uni.setStorageSync("goodsNo", JSON.stringify(dataListNo));

  try {
    let res = await appOrderCreate({ products: data });
    if (res.code == 200) {
      isPay.value = false;
      uni.hideLoading();
      uni.redirectTo({
        url:
          "/pages/cashier/goods_confirm/index?id=" +
          res.data.id +
          "&price=" +
          payPrice.value +
          "&payNum=" +
          payNum.value,
      });

      // let resData = res.data.datas;
    } else {
      uni.showToast({
        title: res.msg,
        icon: "none",
        mask: true,
      });
      isPay.value = false;
      uni.hideLoading();
    }

    console.log(res);
  } catch (e) {
    uni.showToast({
      title: e.msg,
      icon: "none",
      mask: true,
    });
    uni.hideLoading();
    isPay.value = false;
  }
};

const selectNumIndex = ref(-1);
//金额键盘
const inp = (e) => {};

const del = (e) => {
  if (e == 0) {
    selectNumIndex.value = selectNumIndex.value - 1;
  } else if (e == 1) {
    selectNumIndex.value = selectNumIndex.value + 1;
  }
};
const hide = () => {
  // if (num.value > 0) {
  // } else {
  //   jsnum.value = 0;
  // }
  isPayShow.value = false;
};
const keyWordItem = (index) => {
  selectNumIndex.value = index;
};

const confirm = async () => {
  console.log(priceValue.value);
  if (priceValue.value <= 0) {
    uni.showToast({
      title: "请输入金额",
      icon: "none",
    });
    return;
  }
  // getcomputeBrokerage(Number(num.value));
  productDataNo.value[selectNo.value].salePrice = Number(priceValue.value);
  productDataNo.value[selectNo.value].orderNum = 1;

  payPrice.value = operation(
    payPrice.value,
    Number(priceValue.value),
    2,
    "add"
  );
  selectNo.value = selectNo.value + 1;
  payNum.value = payNum.value + 1;
};
const closePay = () => {
  isPayShow.value = false;
  keyWord.value.close();
};

//购物车弹框
const popupshow = ref(false);
const popupopen = () => {
  // popupshow.value = true;
};
const popupclose = () => {
  popupshow.value = false;
};

const clickNum = (item) => {
  if (item.dhCode || item.weight || item.weight > 0) {
    uni.showToast({
      title: "称重商品,请扫码添加",
      icon: "none",
    });

    return;
  }
  item.orderNum = item.orderNum + 1;
  payNum.value = payNum.value + 1;
  payPrice.value = operation(
    payPrice.value,
    item.price ? item.price : item.totalPrice,
    2,
    "add"
  );
};

const goCarPay = () => {
  if (payNum.value > 0) {
    let dataList = [];
    let dataListNo = [];

    productData.value.forEach((item) => {
      if (item.orderNum > 0) {
        dataList.push(item);
      }
    });
    productDataNo.value.forEach((item) => {
      if (item.orderNum > 0 && item.salePrice > 0) {
        dataListNo.push(item);
      }
    });
    uni.setStorageSync("goodsNo", JSON.stringify(dataListNo));

    uni.setStorageSync("goods", JSON.stringify(dataList));

    uni.navigateTo({
      url: "/pages/cashier/goodsPayList/index",
    });
  } else {
    uni.showToast({
      title: "暂无商品,请先选择商品",
      icon: "none",
    });
  }
};

const selectFun = () => {
  if (payNum.value > 0) {
    popupshow.value = !popupshow.value;
  } else {
    uni.showToast({
      title: "请选择商品",
      icon: "none",
    });
  }
};

const valChangeNo = (e) => {
  console.log(e);

  let num = 0;
  let price = 0;

  setTimeout(() => {
    productData.value.forEach((item) => {
      num = num + item.orderNum;
      price = operation(
        price,
        operation(item.orderNum, item.price, 2, "multiply"),
        2,
        "add"
      );
    });
    productDataNo.value.forEach((item) => {
      if (item.orderNum > 0 && item.salePrice > 0) {
        num = num + item.orderNum;
        price = operation(
          price,
          operation(item.orderNum, item.salePrice, 2, "multiply"),
          2,
          "add"
        );
      }
    });

    payPrice.value = price;
    payNum.value = num;
    if (payNum.value == 0) {
      popupshow.value = false;
    }
  }, 100);
};

const valChange = (e) => {
  console.log(e);

  let num = 0;
  let price = 0;
  setTimeout(() => {
    productData.value.forEach((item) => {
      if (item.weight && item.weight > 0) {
        num = num + item.orderNum;
        price = operation(
          price,
          operation(item.orderNum, item.totalPrice, 2, "multiply"),
          2,
          "add"
        );
      } else {
        num = num + item.orderNum;
        price = operation(
          price,
          operation(
            item.orderNum,
            item.price ? item.price : item.totalPrice,
            2,
            "multiply"
          ),
          2,
          "add"
        );
      }
    });
    productDataNo.value.forEach((item) => {
      if (item.orderNum > 0 && item.salePrice > 0) {
        num = num + item.orderNum;
        price = operation(
          price,
          operation(item.orderNum, item.salePrice, 2, "multiply"),
          2,
          "add"
        );
      }
    });

    payPrice.value = price;
    payNum.value = num;
    if (payNum.value == 0) {
      popupshow.value = false;
    }
  }, 100);
};

const clearFun = () => {
  showModal.value = true;
};
//规格滑动
const scrollTop = ref(0);
const upper = (e) => {
  // console.log(e);
};
const lower = (e) => {
  // console.log(e);
};
const scroll = (e) => {
  // console.log(e);
};

// 清空商品
const showModal = ref(false);
const confirmModal = () => {
  productData.value.forEach((item) => {
    item.orderNum = 0;
  });
  productDataNo.value.forEach((item) => {
    item.orderNum = 0;
    item.salePrice = 0;
  });
  payNum.value = 0;
  payPrice.value = 0;
  popupshow.value = false;
  showModal.value = false;
};

// 无码商品
const addNocode = () => {
  selectNo.value = -1;
  productDataNo.value.forEach((item, index) => {
    if (item.orderNum <= 0 || item.salePrice <= 0) {
      selectNo.value = index;
    }
  });

  if (selectNo.value == -1) {
    uni.showToast({
      title: "无码商品已超出",
      icon: "none",
    });
    return;
  }
  priceValue.value = "";
  isPayShow.value = true;
  keyWord.value.open();
};

const searchFun = () => {
  console.log(form.value.keyword);
  getAppStockListQuery(1);
};
const searchFocus = () => {
  // isShowBtn.value = false;
};
const searchBlur = () => {
  // isShowBtn.value = true;
};

const ishowcamera = ref(false);
const addUitCode = () => {
  // #ifdef H5
  uni.navigateTo({
    url: "/pages/code_sand/index?type=addBarCode",
  });
  // #endif
  // #ifndef H5
  // 允许从相机和相册扫码
  // #ifdef APP-PLUS

  const systemInfo = uni.getSystemInfoSync();
  if (systemInfo.osName === "android") {
    if (uni.getStorageSync("isspermission")) {
    } else {
      ishowcamera.value = true;
    }

    plus.android.requestPermissions(["android.permission.CAMERA"], (e) => {
      if (e.deniedAlways.length > 0) {
        // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

        ishowcamera.value = false;
      } else if (e.deniedPresent.length > 0) {
        //权限被临时拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else if (e.deniedAlways.length > 0) {
        //权限被永久拒绝
        // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限
        ishowcamera.value = false;
      } else {
        plus.android.requestPermissions(
          ["android.permission.READ_EXTERNAL_STORAGE"],
          (e) => {
            if (e.deniedAlways.length > 0) {
              // 弹出提示框解释为何需要权限，引导用户打开设置页面开启

              ishowcamera.value = false;
            } else if (e.deniedPresent.length > 0) {
              //权限被临时拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else if (e.deniedAlways.length > 0) {
              //权限被永久拒绝
              // 弹出提示框解释为何需要权限，可再次调用plus.android.requestPermissions申请权限

              ishowcamera.value = false;
            } else {
              ishowcamera.value = false;
              uni.setStorageSync("isspermission", true);

              uni.scanCode({
                scanType: ["barCode", "qrCode"],
                autoDecodeCharset: true,
                autoZoom: true,
                success: function (res) {
                  console.log("条码类型：" + res.scanType);
                  console.log("条码内容：" + res.result);
                  sand_code.value = res.result;
                  getProductByBarCodeFun();
                },
              });
            }
          }
        );
      }
    });
    return;
  }

  // #endif

  uni.scanCode({
    scanType: ["barCode", "qrCode"],
    autoDecodeCharset: true,
    autoZoom: true,
    success: function (res) {
      console.log("条码类型：" + res.scanType);
      console.log("条码内容：" + res.result);
      sand_code.value = res.result;
      getProductByBarCodeFun();
    },
  });
  // #endif
};

const selectCurrent = ref(-1);

const clickTabs = (e) => {
  console.log(e);

  if (e.index == 0) {
    form.value.tag = "hot";
  }
  if (e.index == 1) {
    form.value.tag = "new";
  }
  if (selectCurrent.value == e.index) {
    selectCurrent.value = -1;
    form.value.tag = "";
  } else {
    selectCurrent.value = e.index;
  }

  getAppStockListQuery(1);
};
const logFun = (str = "") => {
  if (str.length > 10) {
    return str.substring(0, 10) + "...";
  } else {
    return str;
  }
};
//无网状态
const connected = () => {
  getAppStockListQuery(1);
  getAppProductNoCode();
};
</script>

<template>
  <jia-PayKeyboard
    :confirmStyle="{ backgroundColor: '#1679FB' }"
    class="keyWord-index"
    :overlayClose="true"
    :sclectItem="selectNumIndex"
    ref="keyWord"
    v-model="priceValue"
    @input="inp"
    @del="del"
    @confirm="confirm"
    @hide="hide"
  >
    <view class="PayKeyboard-k">
      <view class="icon-top">
        <up-icon
          @click="closePay"
          name="close"
          color="#86909C"
          size="30rpx"
        ></up-icon
      ></view>
      <view class="PayKeyboard-k-title"
        ><text>{{ "无码商品" }}</text>
      </view>
      <view class="link-to"></view>
      <view class="PayKeyboard-k-num">
        <view class="PayKeyboard-k-num-title">价格</view>
        <view class="PayKeyboard-k-num-input">
          <up-form labelPosition="left" ref="form1" labelWidth="0">
            <up-form-item
              label=" "
              borderBottom
              ref="item1"
              @click="keyWordItem(-1)"
            >
              <view class="PayKeyboard-k-num-input-text">
                <view
                  class="num-view"
                  v-for="(item, index) in priceValue"
                  :key="index"
                  @click.stop="keyWordItem(index)"
                  ><view class="input_lin" v-if="selectNumIndex == index"></view
                  >{{ item }}</view
                >
                <view class="input_lin" v-if="selectNumIndex == -1"></view>
              </view>

              <template #right>
                <text>元</text>
              </template>
            </up-form-item>
          </up-form>
        </view>
      </view>
    </view>
  </jia-PayKeyboard>

  <topNav
    :title="userInfo.shopName ? logFun(userInfo.shopName) : '手机收银'"
    @save="saveFun"
    rType="customize"
  >
    <template #right>
      <!-- <view
        class="right-plus"
        @click="addNocode"
        v-permission="['shop:product:noCode']"
      >
        <image src="../../../static/cashier/no_code.png" mode="scaleToFill" />
      </view> -->
      <view class="right-plus" @click="addUitCode" style="margin-left: 10rpx">
        <van-icon
          style="font-weight: bold"
          name="scan"
          size="44rpx"
          color="#1D2129"
        />
      </view>
    </template>
  </topNav>
  <view class="content">
    <view class="search" :style="'top: calc( 88rpx + ' + topHeight + 'px);'">
      <view class="search-left">
        <van-icon name="search" class="search-icon" size="36rpx" />
        <input
          type="search"
          confirm-type="search"
          name="search"
          v-model="form.keyword"
          placeholder="输入条码/名称/拼音码/商品编号"
          @confirm="searchFun"
          @focus="searchFocus"
          @blur="searchBlur"
        />
      </view>
      <view class="search-right">
        <up-tabs
          :list="listTab"
          @click="clickTabs"
          :lineColor="selectCurrent >= 0 ? '#1679FB' : '#fff'"
          :current="selectCurrent"
        ></up-tabs>
      </view>
    </view>
    <view class="goods">
      <view
        class="goods-item"
        v-for="(item, index) in productData"
        :key="index"
        @click="clickNum(item)"
      >
        <view class="goods-item-img">
          <text class="goods-item-cz"
            >{{ item.dhCode ? "称重" : "计件" }}
          </text>
          <image
            :src="
              item.image
                ? item.image
                : 'https://cloud-erp.yibaitao.cn/0d2f4178-7754-4686-9213-b174f745258b.png'
            "
            mode="scaleToFill"
          />
        </view>
        <view class="goods-item-info">
          <view class="goods-item-info-title"> {{ item.name }} </view>
          <view class="goods-item-info-price"
            ><text class="price"
              ><text>¥</text>{{ item.price ? item.price : item.totalPrice }}
              <text class="unit">{{
                item.unit ? "/" + item.unit : item.unit
              }}</text></text
            >
            <view class="pay_num">
              <view class="box">
                <up-badge :value="item.orderNum"></up-badge>
              </view>
              <up-icon
                name="plus-circle-fill"
                shape="circle"
                color="#2979ff"
                size="48rpx"
              ></up-icon></view
          ></view>
        </view>
      </view>
    </view>
    <view class="noData" v-if="productData.length <= 0 && !loading">
      <view class="noData-img">
        <image src="@/static/nodate/datas.png" mode="scaleToFill" />
        <view>暂无数据 </view>
      </view>
    </view>
    <!-- <view>12312</view> -->
    <view style="width: 100%; height: 200rpx"></view>
  </view>

  <view
    class="bt_form"
    v-if="!isPayShow && isShowBtn"
    v-permission="['shop:order:create']"
  >
    <view class="bt_form_k">
      <view class="bt_form_k_left">
        <view class="icon_car" @click="goCarPay()">
          <view class="box">
            <up-badge bgColor="#f53f3f" :value="payNum"></up-badge>
          </view>
          <image src="../../../static/cashier/car.png" mode="scaleToFill" />
        </view>
        <view class="price" @click="selectFun()"
          ><text>¥</text>{{ payPrice }}
        </view>
        <view class="num_jt" @click="selectFun()"
          ><up-icon name="arrow-up" color="#ff5722" size="32rpx"></up-icon
        ></view>
      </view>
      <!-- goPay -->
      <view
        class="bt_pay"
        :class="payNum > 0 ? '' : 'no_bt_pay'"
        @click="goCarPay"
        >确认</view
      >
    </view>
  </view>

  <up-popup
    :show="popupshow"
    @close="popupclose"
    @open="popupopen"
    :safeAreaInsetBottom="true"
    round="20"
  >
    <view class="popupcontent">
      <view class="popupcontent-title">
        <text>已选商品</text>
        <view class="popupcontent-title-right" @click="clearFun">
          <up-icon name="trash" color="#86909C" size="32rpx"></up-icon>
          <text>清空</text>
        </view>
      </view>

      <scroll-view
        :scroll-top="scrollTop"
        scroll-y="true"
        class="scroll-Y"
        @scrolltoupper="upper"
        @scrolltolower="lower"
        @scroll="scroll"
      >
        <view v-for="(item, index) in productDataNo" :key="index">
          <view
            class="content-item"
            v-if="item.salePrice > 0 && item.orderNum > 0"
          >
            <view class="content-item-left">
              <image
                src="https://cloud-erp.yibaitao.cn/0d2f4178-7754-4686-9213-b174f745258b.png"
                mode="scaleToFill"
            /></view>
            <view class="content-item-right">
              <view class="content-item-right-title">
                <text>{{ item.name }}</text>
              </view>
              <view class="content-item-right-num">
                <view class="content-item-right-num-left"><text></text> </view>
                <view class="content-item-right-num-right">
                  <up-number-box
                    v-model="item.orderNum"
                    @change="valChangeNo"
                    min="0"
                    max="1"
                  ></up-number-box>
                </view>
              </view>
              <view class="content-item-right-price"
                ><text>¥</text> {{ item.salePrice }}</view
              >
            </view>
          </view>
        </view>
        <view v-for="(item, index) in productData" :key="index">
          <view class="content-item" v-if="item.orderNum > 0">
            <view class="content-item-left"
              ><text class="goods-item-cz"
                >{{ item.dhCode ? "称重" : "计件" }}
              </text>
              <image :src="item.image" mode="scaleToFill"
            /></view>
            <view class="content-item-right">
              <view class="content-item-right-title">
                <text>{{ item.name }}</text>
              </view>
              <view class="content-item-right-num">
                <view class="content-item-right-num-left"
                  ><text>{{ item.categoryName }}</text>
                </view>
                <view class="content-item-right-num-right">
                  <up-number-box
                    v-model="item.orderNum"
                    @change="valChange"
                    min="0"
                    :max="item.weight && item.weight > 0 ? 1 : 9999"
                  ></up-number-box>
                </view>
              </view>
              <view class="content-item-right-price"
                ><text>¥</text>
                {{ item.price ? item.price : item.totalPrice }}</view
              >
            </view>
          </view>
        </view>

        <view style="width: 100%; height: 150rpx"></view>
      </scroll-view>
    </view>
  </up-popup>

  <up-modal
    :show="showModal"
    title="温馨提示"
    :showCancelButton="true"
    confirmText="确认"
    cancelText="取消"
    @cancel="showModal = false"
    @confirm="confirmModal"
  >
    <view class="slot-content">
      <rich-text :nodes="'确定清空选择结算商品？'"></rich-text>
    </view>
  </up-modal>

  <view class="show-camera" v-if="ishowcamera">
    <view class="show-camera-k">
      <view class="show-sm"> 设备权限使用说明 </view>
      <view class="show-des">
        为了给您带来更好的服务，需要获取您的相机权限与读取图片及文件权限，用于更换上传图片、扫一扫等功能，对于您授权的信息我们竭尽全力提供安全保护。
      </view>
    </view>
  </view>
  <noWork @connected="connected"> </noWork>
</template>

<style lang="scss" scoped>
@import "index.scss";
</style>
